<template>
    <div>
        <!-- 面包屑导航条 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
           <!--工具条-->
          <el-form :inline="true" class="toolbar">
            <el-form-item>
              <el-button @click="add" type="success">添加角色</el-button>
            </el-form-item>
          </el-form>
            <el-table :data="roleslist" border stripe style="width: 100%;">
                <el-table-column prop="id" label="角色id" width="100">
                </el-table-column>
                <el-table-column prop="description" label="角色名称" >
                </el-table-column>
                <el-table-column label="状态" width="100">
                    <template slot-scope="scope">
                    <el-tag :type="scope.row.status==1 ? 'danger' : 'primary'"  close-transition>{{scope.row.status==1?'禁用':'启用'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                    <el-button size="small" @click="edit(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--修改-->
           
        </el-card>
         <el-dialog title="修改角色" :visible.sync="editDialogVisible" :close-on-click-modal="false" size="small">
                <el-form :model="editForm" label-position="left" label-width="100px" :rules="inputRule"  ref="editForm">
                    <el-form-item label="名称" prop="name">
                     <el-input v-model="editForm.name"></el-input>
                    </el-form-item>
                 
                    <el-form-item label="权限" prop="rules">
                        <div v-for="(item,index) in editForm.rules" :key="index" >
                                <div>
                                    <el-checkbox @change="handleCheckAllChange" :label="item.id" :indeterminate="editForm.rules[index].indeterminate" v-model="editForm.rules[index].in"
                                    >{{item.name}}
                                    </el-checkbox>
                                </div>
                              <el-checkbox-group v-model="editForm.rules[index].checkedList" @change="checkItemChange" style="margin-left:20px;">
                            <el-checkbox v-for="(child,i) in item.children" :key="child.id" :label="child.id">{{child.name}}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                    <el-switch v-model="editForm.status" active-text="启用" inactive-text="禁用" on-text="启用" off-text="禁用"></el-switch>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editFormSubmit" :loading="editFormLoading">提 交</el-button>
                </div>
          </el-dialog>
          <!--添加-->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" :close-on-click-modal="false" size="small">
      <el-form :model="addForm" label-position="left" label-width="100px"  ref="addForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        
        <el-form-item label="权限" prop="rules">
           <div v-for="(item,index) in addForm.rules" :key="index" >
                                <div>
                                    <el-checkbox @change="handleCheckAllChange2" :label="item.id" :indeterminate="addForm.rules[index].indeterminate" v-model="addForm.rules[index].in"
                                    >{{item.name}}
                                    </el-checkbox>
                                </div>
                              <el-checkbox-group v-model="addForm.rules[index].checkedList" @change="checkItemChange2" style="margin-left:20px;">
                            <el-checkbox v-for="(child,i) in item.children" :key="child.id" :label="child.id">{{child.name}}</el-checkbox>
                            </el-checkbox-group>
                        </div>
         
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addForm.status" on-text="启用" off-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormSubmit" :loading="addFormLoading">提 交</el-button>
      </div>
    </el-dialog>
    </div>
</template>
<script>
export default {
  data() {
    //   const cityOptions = ['上海', '北京', '广州', '深圳'];
    return {
      addForm: {
        id: "",
        name: "",
        rules: [],
        status: true
      },
      checkedCities: ["上海", "北京"],
      cityOptions: ["上海", "北京", "广州", "深圳"],
      cities: ["上海", "北京", "广州", "深圳"],
      checkAll: false,
      isIndeterminate: true,
      permissionListInit: false,
      permissionList: [],
      roleslist: [],
      editDialogVisible: false,
      addDialogVisible: false,
      addFormLoading: false,
      editFormInit: false,
      namelist: "",
      editForm: {
        id: "",
        name: "",
        rules: [],
        status: true
      }
    };
  },
  methods: {
    addFormSubmit() {
      let _data = {
        id: 7247,
        name: this.addForm.name,
        rules: this.getPermissionIds(this.addForm.rules).join(","),
        status: this.addForm.status ? 0 : 1
      };
      console.log(_data);
      this.$http.post("/manage/admin/addRule",_data).then(res => {
        if (res.data.status == 1) {
          this.addDialogVisible = false;
          this.getRolesList();
          this.$message({
            message: "添加成功",
            type: "success"
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    add() {
      // POST

      this.addDialogVisible = true;
      if (this.permissionListInit) {
        this.addPermissionObjInit();
      } else {
        this.getPermission(() => {
          this.addPermissionObjInit();
        });
      }
    },
    getPermission(fn) {
      // alert(2)
      let _data = {};
      this.$http.post("/manage/admin/getAllAdminRules", _data).then(
        res => {
          console.log(res);
          if (res.data.status == 1) {
            this.permissionList = res.data.data;
            this.permissionListInit = true;
            fn && fn();
          }
          // if (1 == response.body.code) {

          // }
        },
        res => {}
      );
    },
    addPermissionObjInit() {
      let _temp = [];
      for (let i = 0; i < this.permissionList.length; i++) {
        _temp.push(
          Object.assign(
            {
              checkedList: [],
              isCheck: false,
              indeterminate: false
            },
            this.permissionList[i]
          )
        );
      }
      console.log(_temp);
      this.addForm.rules = _temp;
    },
    edit(row) {
      console.log(row);
      this.editDialogVisible = true;
      this.editFormInit = true;
      let _data = {
        queryId: row.id
      };
      this.$http.post("/manage/admin/getRoleRulesById", _data).then(res => {
        //  console.log(res)
        this.editFormInit = false;
        this.editForm.id = row.id;
        this.editForm.name = row.description;
        // this.editForm.remark = row.remark
        this.editForm.status = row.status == 0;
        // this.editPermissionObjInit(res.data.data)
        this.editForm.rules = res.data.data;
        console.log(this.editForm.rules);
        this.namelist = res.data.data;
        this.editPermissionObjInit(this.editForm.rules);
      });
    },
    editPermissionObjInit(list) {
      let _temp = [];
      for (let i = 0; i < list.length; i++) {
        _temp.push(Object.assign(_getTempObj(list[i]), list[i]));
      }

      function _getTempObj(list) {
        if (list.in == 0) {
          return {
            checkedList: [],
            indeterminate: false
          };
        } else {
          let _arr = [];
          console.log(list.children);
          if (list.children) {
            for (let i = 0; i < list.children.length; i++) {
              if (list.children[i].in == 1) {
                _arr.push(list.children[i].id);
              }
            }
            return {
              checkedList: _arr,
              indeterminate: _arr.length == list.children.length ? false : true
            };
          }
        }
      }
      console.log(_temp);
      this.editForm.rules = _temp;
    },
    editFormSubmit() {
      let _data = {
        id: this.editForm.id,
        name: this.editForm.name,
        rules: this.getPermissionIds(this.editForm.rules).join(","),
        isClose: this.editForm.status ? 0 : 1
      };
      // console.log(_data);

      this.$http.post("/manage/admin/changeRoleInfo", _data).then(res => {
        // console.log(res);
        if (res.data.status == 1) {
          this.editDialogVisible = false;
          this.getRolesList();
          this.$message({
            message: "修改成功",
            type: "success"
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getPermissionIds(obj) {
      console.log(obj);
      let _arr = [];
      for (let i = 0; i < obj.length; i++) {
        let item = obj[i];
        if (item.in) {
          _arr.push(item.id);
          _arr = _arr.concat(item.checkedList);
        }
      }
      return _arr;
    },
    checkAllChange(event) {
      console.log(event);
      this.checkAllChangeFn(event, "addForm");
    },
    handleCheckAllChange() {
      //   console.log(val);
      this.checkAllChangeFn(event, "editForm");
      // this.checkedCities = val ? this.cityOptions : [];
      // this.isIndeterminate = false;
      // if()
    },
    handleCheckAllChange2() {
      this.checkAllChangeFn(event, "addForm");
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    checkAllChangeFn(event, form) {
      console.log(event);
      console.log(this[form].rules);
      for (let i = 0; i < this[form].rules.length; i++) {
        let item = this[form].rules[i];
        if (item.id == event.target.value) {
          item.indeterminate = false;
          item.checkedList = event.target.checked
            ? (() => {
                let _arr = [];
                for (let i = 0; i < item.children.length; i++) {
                  _arr.push(item.children[i].id);
                }
                return _arr;
              })()
            : [];
        }
      }
    },
    checkItemChange(value) {
      this.checkItemChangeFn(value, "editForm");
    },
    checkItemChange2(value) {
      this.checkItemChangeFn(value, "addForm");
    },
    checkItemChangeFn(value, form) {
      for (let i = 0; i < this[form].rules.length; i++) {
        let item = this[form].rules[i];
        if (item.checkedList.length == item.children.length) {
          item.in = true;
          item.indeterminate = false;
        } else if (item.checkedList.length == 0) {
          item.in = false;
          item.indeterminate = false;
        } else {
          item.in = true;
          item.indeterminate = true;
        }
      }
    },
    // checkAllChangeFn(event, form) {
    //   console.log(event);

    //   for (let i = 0; i < this[form].permissionObj.length; i++) {
    //     let item = this[form].permissionObj[i];
    //     // console.log(item)
    //     if (item.id == event.target.value) {
    //       console.log(item.checkedList);
    //       //   item.indeterminate = true
    //       item.in = 1;
    //       if (item.checkedList.length == 0) {
    //         let _arr = [];
    //         for (let i = 0; i < item.children.length; i++) {
    //           _arr.push(item.children[i].id);
    //         }
    //         item.checkedList = _arr;
    //       } else {
    //         //   item.in = 0
    //         item.indeterminate = false;
    //         item.checkedList = event.target.checked
    //           ? (() => {
    //               let _arr = [];
    //               for (let i = 0; i < item.children.length; i++) {
    //                 _arr.push(item.children[i].id);
    //               }
    //               return _arr;
    //             })()
    //           : [];
    //       }
    //     }
    //   }
    // },
    getRolesList() {
      // POST
      this.$http.post("/manage/admin/getAllRuleGroup").then(res => {
        // console.log(res)
        if (res.data.status == 1) {
          this.roleslist = res.data.data;
          console.log(this.roleslist);
        } else {
          this.$message.error(res.data.message);
        }
      });
      // const { data: res } = await this.$http.get('roles')
      // if (res.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      // this.roleslist = res.data
      // console.log(res.data)
    }
  },
  mounted() {
    this.getRolesList();
  }
};
</script>
